package com.yinghuo.risk.frigate.web.component;

import com.alibaba.fastjson.JSON;
import com.yinghuo.risk.frigate.core.handler.CacheHandler;
import com.yinghuo.risk.frigate.web.dao.CacheRepository;
import com.yinghuo.risk.frigate.web.entity.CacheEntity;
import com.yinghuo.risk.frigate.web.entity.UserInfoEntity;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Optional;

/**
 * com.yinghuo.risk.frigate.web.component
 *
 * @author 白雨浓
 * date: 2018/10/18 14:21
 * content:
 */
@Component
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@SuppressWarnings("unchecked")
public class CacheHandlerComponent implements CacheHandler<UserInfoEntity> {

    private final CacheRepository cacheRepository;

    @Override
    public UserInfoEntity find(String key) {

        Optional<CacheEntity> optional = cacheRepository.findById(key);

        if (!optional.isPresent()) {
            return null;
        }

        CacheEntity cacheEntity = optional.get();

        if (StringUtils.isEmpty(cacheEntity.getValue())) {
            return null;
        }

        return JSON.parseObject(cacheEntity.getValue(), UserInfoEntity.class);
    }

    @Override
    public void create(String key, UserInfoEntity info) {

        CacheEntity entity = new CacheEntity();
        entity.setKey(key);
        entity.setValue(JSON.toJSONString(info));

        cacheRepository.save(entity);
    }

    @Override
    public void modify(String key, UserInfoEntity info) {
        CacheEntity entity = new CacheEntity();
        entity.setKey(key);
        entity.setValue(JSON.toJSONString(info));

        cacheRepository.save(entity);
    }

    @Override
    public UserInfoEntity remove(String key) {

        Optional<CacheEntity> optional = cacheRepository.findById(key);

        if (!optional.isPresent()) {
            return null;
        }

        cacheRepository.deleteById(key);

        CacheEntity cacheEntity = optional.get();

        if (StringUtils.isEmpty(cacheEntity.getValue())) {
            return null;
        }

        return JSON.parseObject(cacheEntity.getValue(), UserInfoEntity.class);
    }

    @Override
    public void refresh(String key) {

    }
}
